<?php

namespace app\api\controller;

use cmf\controller\AdminBaseController;
use think\Db;

class AdminGuestbookController extends AdminBaseController
{
    
    // 后台留言列表
    public function index(){
        $where = [
            'status'  => 1,
            'site_id' => get_site_id(),
        ];

        $filter = $this->request->param();

        $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
        $endTime   = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);

        if (!empty($startTime) && !empty($endTime)) {
            $where['createtime'] = [['>=', $startTime], ['<=', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['createtime'] = ['>=', $startTime];
            }
            if (!empty($endTime)) {
                $where['createtime'] = ['<=', $endTime];
            }
        }

        $data = db('guestbook')
             -> where($where)
             -> order("createtime DESC")
             -> paginate(20)
             -> each(function($item, $key){
                $item['createtime'] = empty($item['createtime'])? '' : date('Y-m-d H:i',$item['createtime']) ;
                return $item;
        });
        // echo db()->getLastsql();

        $this->assign('start_time', isset($filter['start_time']) ? $filter['start_time'] : '');
        $this->assign('end_time', isset($filter['end_time']) ? $filter['end_time'] : '');
        $this->assign('filter', $filter);
        $this->assign('lists', $data->items());
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    // 查看留言
    public function edit()
    {
        $id   = $this->request->param('id', 0, 'intval');
        $data = db('guestbook')->where('id', $id)->find();
        $data['createtime'] = empty($data['createtime'])? '-' : date('Y-m-d H:i',$data['createtime']) ;

        $this->assign('data', $data);

        return $this->fetch();   
    }

    // 删除留言
    public function delete(){
        $param           = $this->request->param();

        if (isset($param['id'])) {
            $id     = $this->request->param('id', 0, 'intval');
            $result = db('guestbook')->where('id', $id)->delete();
        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $result = db('guestbook')->where(['id' => ['IN', $ids]])->delete();
        }

        if( $result ){
            $this->success("删除成功！");
        }else{
            $this->error('删除失败！');
        }
    }
}
